package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"golang.org/x/sync/errgroup"
)

func main() {
	g, ctx := errgroup.WithContext(context.Background())

	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "world")
	})

	server := &http.Server{
		Addr:    ":9090",
		Handler: mux,
	}

	g.Go(func() error {
		return server.ListenAndServe()
	})

	g.Go(func() error {
		<-ctx.Done()
		fmt.Println("errgroup done, shutting down...")
		return server.Shutdown(context.TODO())
	})

	g.Go(func() error {
		quit := make(chan os.Signal, 1)
		signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

		select {
		case <-ctx.Done():
			fmt.Println("errgroup exit...")
			return ctx.Err()
		case <-quit:
			fmt.Println("received quit signal")
			return errors.New("received quit signal")
		}
	})

	if err := g.Wait(); err != nil {
		fmt.Println("errgroup exit.")
	}
}
